package com.softeem.controller;

import com.github.pagehelper.PageInfo;
import com.softeem.pojo.Blog;
import com.softeem.service.BlogService;
import com.softeem.util.FileUtil;
import com.softeem.util.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Slf4j
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;


    @Autowired
    private FileUtil fileUtil;


    @GetMapping("/blogList")
    public PageInfo<Blog> blogs(@RequestParam(name = "page",defaultValue = "1") int page,
                                @RequestParam(name="limit",defaultValue = "3") int limit,
                                @RequestParam("userId")int userId) {
        log.info("------请求展示的userId----"+userId);
        log.info("------请求展示的page-----"+page);
        log.info("------请求展示limit-----"+limit);
        return blogService.getBlogListLimit(page,limit,userId);
    }


    @PostMapping("/addBlog")
    public ResultBean blogs(@RequestBody  Blog blog) {
        log.info("------blog----"+blog);
        blog.setCreated(new Date()); //设置发布时间
        return blogService.addBlog(blog)>0?ResultBean.success("发布成功"):ResultBean.fail("发布失败");
    }



    @RequestMapping("/uploadImage")
    public ResultBean uploadImg(@RequestParam("file") MultipartFile file){
        log.info("文件上传");
        if(!file.isEmpty()) {
            //调用工具类中的方法，将file存入到D盘的目录中
            String fileName = fileUtil.storeFile(file);
            // 文件上传成功，返回的是虚拟路径
            return ResultBean.success("/upload/"+fileName);
        }
        return ResultBean.fail("上传失败");
    }

}
